package org.apogee.mil.client.main;

import org.apogee.mil.client.main.pages.LoginForm;
import org.apogee.mil.client.main.pages.LogoutForm;
import org.apogee.mil.client.main.pages.admin.AdminPanel;
import org.apogee.mil.client.main.pages.superuser.SuperUserPanel;
import org.apogee.mil.client.main.pages.trainee.TraineePanel;
import org.apogee.mil.client.main.pages.trainer.TrainerPanel;
import org.apogee.mil.client.portal.PortalForm;
import org.apogee.mil.shared.User;

import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.TabItem;
import com.extjs.gxt.ui.client.widget.TabPanel;
import com.google.gwt.user.client.Element;

public class MainForm extends LayoutContainer {

	private User currentUser;
	private TabPanel panel = null;
	private TabItem login = null;
	private PortalForm portalForm;

	public MainForm(PortalForm portalForm) {
		this.portalForm = portalForm;
	}


	@Override
	protected void onRender(Element parent, int pos) {
		super.onRender(parent, pos);
		panel = new TabPanel();
		panel.setMinTabWidth(125);
		panel.setResizeTabs(true);
		panel.setAnimScroll(true);
		panel.setTabScroll(true);
		panel.setCloseContextMenu(true);
		panel.setHeight(parent.getOffsetHeight());
		panel.setWidth(parent.getOffsetWidth());

		login = new TabItem("Login");
		login.add(new LoginForm(this));
		panel.add(login);
		
		add(panel);
		
		layout();

	}


	public void enableFrames(User result) {
		this.currentUser = result;
		showTabs();
		layout();
		panel.setSelection(panel.getItem(1));
		portalForm.getMessages(this.currentUser);
	}

	private void showTabs() {
		login.disable();
		TabItem item = new TabItem("Training");
		item.add(new TraineePanel());
		panel.add(item);

		if (currentUser.getAccessLevel() < 3) {
			item = new TabItem("Trainer");
			item.add(new TrainerPanel());
			panel.add(item);
		}

		if (currentUser.getAccessLevel() < 2) {
			item = new TabItem("Admin");
			item.add(new AdminPanel());
			panel.add(item);
		}

		if (currentUser.getAccessLevel() < 1) {
			item = new TabItem("Super User");
			item.add(new SuperUserPanel().asWidget());
			panel.add(item);
		}

		item = new TabItem("Log out");
		item.add(new LogoutForm(this));
		panel.add(item);
	}

	public void hideTabs() {
		portalForm.clearMessages();
		panel.removeAll();
		login = new TabItem("Login");
		login.add(new LoginForm(this));
		panel.add(login);
		layout();
		panel.setSelection(panel.getItem(0));
	}

}
